<?php
/**
 *  * 系统-受国家计算机软件著作权保护 - !
 * =========================================================
 * Copy right 2018-2025 成都海之心科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.ohyu.cn
 * 这不是一个自由软件！在未得到官方有效许可的前提下禁止对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * User: ohyueo
 * Date: 2021/5/29
 * Time: 15:16
 */

namespace app\api\controller;
use app\BaseController;
use app\api\models\EscortUserList;
use app\api\models\EscortUserLogin;
use app\api\models\EscortUserInfo;
use app\validate\api\reg;
use think\facade\Db;
use think\Request;
use app\handler\EasySmsHandler;
use app\validate\api\loginin;
use app\handler\MoneyLogHandler;


class Login extends BaseController
{
    //发送验证码
    public function sendmsg(Request $request){
        $data = $request->post();
        // 检验数据
        validate(reg\VerifyPhoneValidate::class)->check($data);


        if (env('app_debug')) {
            // 如果是调试模式，则不用发短信
            $code = 123456;
        }else{
            // 随机验证码
            $code = str_pad(random_int(1, 999999), 6, 0, STR_PAD_RIGHT);
            // 发送短信
            $params = [
                'mobile' => $data['mobile'],
                'code' => $code,
                'type' => $data['type']
            ];
            //发送验证码
            $res=EasySmsHandler::send($params['mobile'], $params['code'], $params['type']);
            if(!$res && !$res['code']){
                return $this->message($res['message'],[],403);
            }
        }
        // 缓存30分钟
        cache($data['mobile'] . '_verification', $code, 1800);

        return $this->message('发送成功');
    }
    //手机号登录
    public function mobileCodeLogin(Request $request){
        $data = $request->post();
        // 检验数据
        validate(reg\MobileCodeLoginValidate::class)->check($data);
        $code = cache($data['mobile'] . '_verification');
        if (!$code) {
            return $this->message('验证码已过期', [], 0);
        }
        if (!hash_equals($data['code'], $code)) {
            // 返回401
            return $this->message('验证码错误', [], 0);
        }
        // 删除缓存
        cache($data['mobile'] . '_verification', null);
        try {
            //根据app\models\BaseModel.php中的查询单条数据
            $user = EscortUserLogin::findData(['where'=>['mobile'=>$data['mobile']]]);
            //$user = EscortUserLogin::whereMobile($data['mobile'])->find();
            if ($user) {
                //$user=EscortUserList::find($user->uid);
                $user=EscortUserList::findData(['where'=>['id'=>$user->uid]]);
                $userid=$user->id;
                $name=$user->nick;
                if(!$name){
                    $name='默认用户'.$userid;
                }
                $headimg=$user->headimg;
                if($headimg){
                    $himg=getFullImageUrl($headimg);
                }else{
                    $himg=getFullImageUrl('/storage/imges/mo.png');
                }
                // 登录成功
                if ($user->status==2) {
                    // 账号被禁止登录
                    return $this->message($user->forbid_msg ?: '该账户已被禁止登陆', [], 0);
                }
            } else {
                // 注册
                $urr=[
                    'nick' => '默认用户',
                    'money' => 0
                ];
                //$user = EscortUserList::create($urr);
                //根据app\models\BaseModel.php中的添加数据
                $user = EscortUserList::addData($urr);
                $city='';
                $province='';
                $ip=getip();
                $map = new \app\common\Map();
                $res = $map->getmapip($ip);
                if($res && $res['status']==0){
                    $city=$res['result']['ad_info']['city'];
                    $province=$res['result']['ad_info']['province'];
                    event('RegProvince', ['province'=>$province]);
                }
                // 获取自增ID
                $userid=$user->id;
                //登录表
                $loarr=[
                    'uid' => $userid,
                    'reg_time' => gettime(),
                    'mobile' => $data['mobile'],
                    'reg_ip' => getip(),
                    'reg_city' => $city,
                    'reg_province' => $province
                ];
                //EscortUserLogin::create($loarr);
                //根据app\models\BaseModel.php中的添加数据
                EscortUserLogin::addData($loarr);
                //详情
                $iarr=[
                    'user_id' => $userid
                ];
                //EscortUserInfo::create($iarr);
                //根据app\models\BaseModel.php中的添加数据
                EscortUserInfo::addData($iarr);
                $name='默认用户'.$userid;
                $himg=getFullImageUrl('/storage/imges/mo.png');
            }
            //赠送积分
            $sno=getMerConfig('-systemsite.sys_perfectuser')?:0;
            if($sno && !$user->userinfo->firstinte){
                //赠送积分
                $user->integral+=$sno;
                $user->save();
                //积分记录
                $text='注册用户信息赠送'.$sno.'积分';
                MoneyLogHandler::addint($user,$sno,1,1,$text);
                $user->userinfo->firstinte=1;
                $user->userinfo->save();
            }

            $token = $this->saveToken($user);   //生成token
            $userlist=array('name'=>$name,'id'=>$userid,'headimg'=>$himg);
            return $this->message('登录成功', ['token' => $token,'userlist'=>$userlist]);
         } catch (\Exception $e) {
             return $this->message('登录失败'.$e->getMessage, [], 0);
         }
    }
    /**
     * 注册
     *
     * @param Request $request
     * @return \think\response\Json
     */
    public function register(Request $request)
    {   
        exit;
        $data = $request->post();
        // 验证数据
        validate(reg\RegisterValidate::class)->check($data);
        $code = cache($data['mobile'] . '_verification');
        if (!$code) {
            return $this->message('验证码已过期', [], 0);
        }
        if (!hash_equals($data['code'], $code)) {
            // 返回401
            return $this->message('验证码错误', [], 0);
        }
        // 删除缓存
        cache($data['mobile'] . '_verification', null);
        try {
            // 注册
            // $user = EscortUserList::create([
            //     'nick' => '默认用户',
            //     'money' => 0
            // ]);
            //根据app\models\BaseModel.php中的添加数据
            $user = EscortUserList::addData(['nick' => '默认用户','money' => 0]);
            $city='';
            $province='';
            $ip=getip();
            $map = new \app\common\Map();
            $res = $map->getmapip($ip);
            if($res && $res['status']==0){
                $city=$res['result']['ad_info']['city'];
                $province=$res['result']['ad_info']['province'];
                event('RegProvince', ['province'=>$province]);
            }else{
                //接口异常 通知管理员
                $message=$res['message'];
                event('LogMessage', ['type'=>'getmapip','msg'=>$message]);
            }
            // 获取自增ID
            $userid=$user->id;
            //登录表
            // EscortUserLogin::create([
            //     'uid' => $userid,
            //     'reg_time' => gettime(),
            //     'mobile' => $data['mobile'],
            //     'password' => password_hash($data['password'], PASSWORD_DEFAULT ),
            //     'reg_ip' => $ip,
            //     'reg_city' => $city,
            //     'reg_province' => $province
            // ]);
            //根据app\models\BaseModel.php中的添加数据
            EscortUserLogin::addData([
                'uid' => $userid,
                'reg_time' => gettime(),
                'mobile' => $data['mobile'],
                'password' => password_hash($data['password'], PASSWORD_DEFAULT ),
                'reg_ip' => $ip,
                'reg_city' => $city,
                'reg_province' => $province
            ]);
            EscortUserInfo::addData([
                'user_id' => $userid
            ]);
            $token = $this->saveToken($user);   //生成token
            return $this->message('注册成功', ['token' => $token]);
        } catch (\Exception $e) {
            // 注册失败,计入日志
            return $this->message('注册失败', [], 500);
        }
    }
    //用户+密码注册
    public function reg_username(Request $request){
        exit;
        $data = $request->post();
        $username=strip_tags(trim($data['user']));//用户名
        $pwd=strip_tags(trim($data['pwd']));//密码
        if(!$username){
            return $this->message('用户名不能为空', [], 0);
        }
        if(!$pwd){
            return $this->message('密码不能为空', [], 0);
        }
        // 注册
        $user = EscortUserList::addData([
            'nick' => '默认用户',
            'money' => 0
        ]);
        $city='';
        $province='';
        $ip=getip();
        $map = new \app\common\Map();
        $res = $map->getmapip($ip);
        if($res && $res['status']==0){
            $city=$res['result']['ad_info']['city'];
            $province=$res['result']['ad_info']['province'];
            event('RegProvince', ['province'=>$province]);
        }else{
            //接口异常 通知管理员
            $message=$res['message'];
            event('LogMessage', ['type'=>'getmapip','msg'=>$message]);
        }
        // 获取自增ID
        $userid=$user->id;
        //登录表
        EscortUserLogin::addData([
            'uid' => $userid,
            'reg_time' => gettime(),
            'username' => $username,
            'password' => password_hash($data['pwd'], PASSWORD_DEFAULT ),
            'reg_ip' => $ip,
            'reg_city' => $city,
            'reg_province' => $province
        ]);
        EscortUserInfo::addData([
            'user_id' => $userid
        ]);
        $token = $this->saveToken($user);   //生成token
        return $this->message('注册成功', ['token' => $token]);
    }
    //用户名+密码登录
    public function login_username(Request $request){
        exit;
        $data = $request->post();
        $username=strip_tags(trim($data['user']));//用户名
        $pwd=strip_tags(trim($data['pwd']));//密码
        if(!$username){
            return $this->message('用户名不能为空', [], 0);
        }
        if(!$pwd){
            return $this->message('密码不能为空', [], 0);
        }
        //$user = Db::name('user_login')->where('username|password', $username)->field(['password','uid'])->find();
        //根据app\models\BaseModel.php中的查询单条数据
        $user = EscortUserLogin::findData(['where'=>['username|password'=>$username],'field'=>['password','uid']]);
        if ($user) {
            if (!password_verify($data['pwd'], $user['password'])) {
                return $this->message('密码错误', [], 0);
            }
            //$user=EscortUserList::find($user['uid']);
            //根据app\models\BaseModel.php中的查询单条数据
            $user=EscortUserList::findData(['where'=>['id'=>$user['uid']]]);
            // 登录成功
            if ($user->status==2) {
                // 账号被禁止登录
                return $this->message($user->forbid_msg ?: '该账户已被禁止登陆', [], 0);
            }
        }else{
            return $this->message('该用户不存在', [], 0);
        }
        //
        $token = $this->saveToken($user);   //生成token
        return $this->message('登录成功', ['token' => $token]);
    }
    /**
     * 找回密码
     *
     * @param Request $request
     * @return \think\response\Json
     */
    public function findPassword(Request $request)
    {
        $data = $request->put();
        // 验证数据
        validate(loginin\FindPasswordValidate::class)->check($data);
        $code = cache($data['mobile'] . '_verification');
        if (!$code) {
            abort(403, '验证码已过期');
        }
        if (!hash_equals($data['code'], $code)) {
            // 返回401 清除缓存
            abort(401, '验证码错误');
        }
        // 删除缓存
        cache($data['mobile'] . '_verification', null);
        // 修改密码
        // EscortUserLogin::where('mobile', $data['mobile'])->update([
        //     'password' => password_hash($data['password'], PASSWORD_DEFAULT),
        //     'password_error' => 0
        // ]);
        //根据app\models\BaseModel.php中的修改数据
        EscortUserLogin::updatesData(['where'=>['mobile'=>$data['mobile']],'data'=>['password'=>password_hash($data['password'], PASSWORD_DEFAULT),'password_error'=>0]]);
        return $this->message('修改成功');
    }
    /**
     * 生成并保存token
     *
     * @param $user
     * @return string
     */
    public function saveToken($user)
    {
        // 登录成功,生成新的 token
        $token = md5(time() . $user->id);
        // 插入一条 token 数据
        $new=gettime();
        $ohyu_merid=session('ohyu_merid');
        if($ohyu_merid){
            $tokenarr=['token' => $token,'user_id'=>$user->id,'update_time'=>$new,'merid'=>$ohyu_merid];
        }else{
            $tokenarr=['token' => $token,'user_id'=>$user->id,'update_time'=>$new];
        }
        $user->userToken()->save($tokenarr);
        //添加更新时间
        $user->update_time=date('Y-m-d H:i:s');
        //将用户信息存入缓存
        cache($token, $user, 86400*7);
        //兼容PC网页版 把token存入cookie
        cookie('user_cookie', $token, 7*24*3600);//七天
        //兼容小程序 记录一个session
        $ohyu_merid = input('param.ohyu_merid');
        session('ohyu_merid', $ohyu_merid,7*24*3600);
        return $token;
    }
}